import {
  UpCircleOutlined,
  DownCircleOutlined,
  FormOutlined,
  DeleteOutlined,
  ImportOutlined,
} from '@ant-design/icons'
import { type RequiredFields } from '@gnlab/utils'
import { Button, Tooltip } from 'antd'
import c from 'classnames'
import {
  type Word,
  type WordType,
  generalWordTypes,
  wordTitleMap,
} from '@/services/common/definition'
import './index.module.less'
import { EditWord } from '../edit'
import { ImportFromLibrary } from '../library/import'
import { PreviewWord } from '../preview'
import { getWordId, useEdit } from './hooks'

export function WordsInput(props: {
  value?: Word[]
  onChange?: (value: Word[]) => void
  extraTypes?: WordType[]
  disableTypes?: WordType[]
  enableLibrary?: boolean // 是否支持从话术库中选择内容
  placeholder?: JSX.Element // words 为空时显示的占位内容
  editorProps?: Partial<Record<WordType, Record<string, unknown>>> // 传递给指定类型 editor 的定制 props
  limit?: number // 指定最大条数
}) {
  const {
    value: words,
    onChange,
    extraTypes,
    disableTypes,
    enableLibrary = false,
    placeholder,
    editorProps,
    limit,
  } = props as RequiredFields<typeof props, 'value' | 'onChange'>

  const wordTypes = useMemo(() => {
    let types = [...generalWordTypes, ...(extraTypes ?? [])]
    if (disableTypes) types = types.filter(type => !disableTypes.includes(type))
    return types
  }, [extraTypes, disableTypes])

  const {
    goUp,
    goDown,
    remove,
    editing,
    setEditing,
    save: edited,
    cancel: cancelEdit,
  } = useEdit(words, onChange)

  const limited = typeof limit === 'number' && words.length >= limit

  const [importing, setImporting] = useState(false)
  function imported(newWords?: Word[]) {
    setImporting(false)
    if (newWords && newWords.length) {
      const endIndex = limit
      onChange([...words, ...newWords].slice(0, endIndex))
    }
  }

  return <div>
    <div styleName="types">
      {enableLibrary ? (
        <Tooltip title="已达最大数量，无法再添加" {...(limited ? {} : { open: false })}>
          <Button
            size="small"
            type="primary"
            icon={<ImportOutlined />}
            onClick={() => setImporting(true)}
            disabled={limited}
          >
            话术库
          </Button>
        </Tooltip>
      ) : null}

      {wordTypes.map(type => <Tooltip
        key={type}
        title="已达最大数量，无法再添加"
        {...(limited ? {} : { open: false })}
      >
        <Button type="link" disabled={limited} onClick={() => setEditing(type)}>
          {wordTitleMap[type]}
        </Button>
      </Tooltip>)}
    </div>

    {!words.length && placeholder ? placeholder : null}

    {words.map((word, index) => {
      const canGoUp = index > 0
      const canGoDown = index < words.length - 1
      return <div key={getWordId(word)} styleName="word-item">
        <PreviewWord word={word} />

        <div styleName="actions">
          <UpCircleOutlined styleName={c(!canGoUp && 'disabled')} onClick={() => goUp(index)} />
          <DownCircleOutlined
            styleName={c(!canGoDown && 'disabled')}
            onClick={() => goDown(index)}
          />
          <FormOutlined styleName="edit" onClick={() => setEditing(index)} />
          <DeleteOutlined styleName="delete" onClick={() => remove(index)} />
        </div>
      </div>
    })}

    <EditWord
      editing={typeof editing === 'number' ? words[editing]! : editing}
      customize={editorProps}
      onSave={edited}
      onCancel={cancelEdit}
    />
    <ImportFromLibrary types={wordTypes} importing={importing} onFinish={imported} />
  </div>
}
